package pers.qianyu.module.system.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import pers.qianyu.module.core.constants.TokenConstants;
import pers.qianyu.module.core.domain.system.vo.SysUserVO;
import pers.qianyu.module.system.listener.events.SysUserInfoUpdatedEvent;
import pers.qianyu.module.system.service.SysUserService;

import java.util.Objects;

/**
 * 用户信息更新监听器
 *
 * @author mizzle rain
 * @date 2021-04-06 14:16
 */
@Component
public class SysUserInfoUpdatedListener implements ApplicationListener<SysUserInfoUpdatedEvent> {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private SysUserService sysUserService;

    @Override
    public void onApplicationEvent(SysUserInfoUpdatedEvent sysUserInfoUpdatedEvent) {
        Long userId = sysUserInfoUpdatedEvent.getUserId();
        Object token = redisTemplate.opsForValue().get(TokenConstants.USER_ID_PREFIX + userId);
        if (Objects.nonNull(token)) {
            Object value = redisTemplate.opsForValue().get(token);
            if (Objects.nonNull(value)) {
                SysUserVO sysUserVO = sysUserService.queryById(userId);
                redisTemplate.opsForValue().set((String) token, sysUserVO, TokenConstants.TOKEN_EXPIRE_TIME);
            }
        }
    }
}
